<?php

/**
 * @file
 * Webform module telephone component.
 */

/**
 * Implements _webform_defaults_component().
 */
function _webform_defaults_telephone() {
  return array(
    'name' => '',
    'form_key' => NULL,
    'pid' => 0,
    'weight' => 0,
    'value' => '',
    'mandatory' => 0,
    'extra' => array(
      //'country_textfield' => 1,
      //'area_textfield' => 1,
	  //'ext_textfield' => 0,
      'phone_textfield' => 1,
	  'mobile_textfield' => 0,
      //'datepicker' => 1,
      'title_display' => 0,
      'description' => '',
      'private' => FALSE,
    ),
  );
}

/**
 * Implements _webform_theme_component().
 */
function _webform_theme_telephone() {
  return array(
    'webform_telephone' => array(
      'render element' => 'element',
      'file' => 'components/telephone.inc',
    ),
    'webform_display_telephone' => array(
      'render element' => 'element',
      'file' => 'components/telephone.inc',
    ),
  );
}

/**
 * Implements _webform_edit_component().
 */
function _webform_edit_telephone($component) {
  $form = array();
  $form['value'] = array(
    '#type' => 'textfield',
    '#title' => t('Default value'),
    '#default_value' => $component['value'],
    '#description' => t('The default value of the field.'),
    '#size' => 60,
    '#maxlength' => 127,
    '#weight' => 0,
  );

  /*$form['display']['datepicker'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable popup calendar'),
    '#default_value' => $component['extra']['datepicker'],
    '#description' => t('Enable a JavaScript date picker next to the date field.'),
    '#weight' => 2,
    '#parents' => array('extra', 'datepicker'),
  );*/
  /*$form['display']['country_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for Country Code'),
    '#default_value' => $component['extra']['country_textfield'],
    '#description' => t('If checked'),
    '#weight' => 2,
    '#parents' => array('extra', 'country_textfield'),
  );
  $form['display']['area_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for Area Code'),
    '#default_value' => $component['extra']['area_textfield'],
    '#description' => t('If checked'),
    '#weight' => 3,
    '#parents' => array('extra', 'area_textfield'),
  );
  $form['display']['ext_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a textfield for phone ext'),
    '#default_value' => $component['extra']['ext_textfield'],
    '#description' => t('If checked'),
    '#weight' => 5,
    '#parents' => array('extra', 'ext_textfield'),
  );*/
  
  $form['display']['phone_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a Telephone Number.'),
    '#default_value' => $component['extra']['phone_textfield'],
    //'#description' => t('If checked,'),
    '#weight' => 4,
    '#parents' => array('extra', 'phone_textfield'),
  );
  $form['display']['mobile_textfield'] = array(
    '#type' => 'checkbox',
    '#title' => t('Dispaly a Mobile Number.'),
    '#default_value' => $component['extra']['mobile_textfield'],
    //'#description' => t('If checked'),
    '#weight' => 6,
    '#parents' => array('extra', 'mobile_textfield'),
  ); 

  return $form;
}

/**
 * Implements _webform_render_component().
 */
function _webform_render_telephone($component, $value = NULL, $filter = TRUE) {
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;

  $element = array(
    '#type' => 'telephone',
    '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
    '#weight' => $component['weight'],
    '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
    '#required' => $component['mandatory'],
    //'#country_textfield' => $component['extra']['country_textfield'],
	//'#area_textfield' => $component['extra']['area_textfield'],
	//'#ext_textfield' => $component['extra']['ext_textfield'],
	'#phone_textfield' => $component['extra']['phone_textfield'],
	'#mobile_textfield' => $component['extra']['mobile_textfield'],
    '#default_value' => $filter ? _webform_filter_values($component['value'], $node, NULL, NULL, FALSE) : $component['value'],
    '#process' => array('webform_expand_telephone'),
    '#theme' => 'webform_telephone',
    '#theme_wrappers' => array('webform_element'),
    '#element_validate' => array('webform_validate_telephone'),
    '#translatable' => array('title', 'description'),
  );

  /*if ($component['extra']['datepicker']) {
    $element['#datepicker'] = TRUE;
    $element['#attached'] = array(
      'library' => array(
        array('system', 'ui.datepicker'),
      ),
    );
  }*/

  // Set the value from Webform.
  if (isset($value[0]) && $value[0] !== '') {
    $type  = ($element['#mobile_textfield']) ? "mobile" : "phone";
	$value = webform_telephone_array($value[0], $type);
    $element['#default_value'] = $value;
  }
  
  //print_r($element);exit;
  return $element;
}

// Convert an telephone string into an array.
function webform_telephone_array($string, $type='phone') {
  $return = array();
  
  $matches = explode("|", $string);
  if ($type == 'phone') {
    $return['country'] = isset($matches[0]) ? trim($matches[0]) : '';
    $return['area'] = isset($matches[1]) ? trim($matches[1]) : '';
    $return['phone'] = isset($matches[2]) ? trim($matches[2]) : '';
	$return['ext'] = isset($matches[3]) ? trim($matches[3]) : '';
  }
  elseif ($type == 'mobile') {
	$return['country'] = isset($matches[0]) ? trim($matches[0]) : '';
	$return['mobile'] = isset($matches[1]) ? trim($matches[1]) : '';
  }

  return $return;
}


/**
 * Form API #process function for Webform telephone fields.
 */
function webform_expand_telephone($element) {
  // Accept a string or array value for #default_value.
  if (!empty($element['#default_value']) && is_string($element['#default_value'])) {
    $type  = ($element['#mobile_textfield']) ? "mobile" : "phone";
	$element['#default_value'] = webform_telephone_array($element['#default_value'], $type);
  }

  // Set defaults according to existing #default_value (set by Form API)
  $default_values = array(
      'country' => isset($element['#default_value']['country']) ? $element['#default_value']['country'] : NULL,
      'area' => isset($element['#default_value']['area']) ? $element['#default_value']['area'] : NULL,
      'phone' => isset($element['#default_value']['phone']) ? $element['#default_value']['phone'] : NULL,
	  'ext' => isset($element['#default_value']['ext']) ? $element['#default_value']['ext'] : NULL,
	  'mobile' => isset($element['#default_value']['mobile']) ? $element['#default_value']['mobile'] : NULL,
  );

  // Let Drupal do it's normal expansion.
  //$element = form_process_date($element);	print_r($element);exit;
  if (empty($element['#value'])) {
    $element['#value'] = array(
      'country' => 'country',
      'area' => 'area',
      'phone' => 'phone',
	  'ext' => 'ext',
	  'mobile' => 'mobile',
    );
  }
  $element['country'] = array(
    '#type' => 'textfield',
    '#title' => t('Country Code'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['country'],
    '#attributes' => $element['#attributes'],
  );
  $element['area'] = array(
    '#type' => 'textfield',
    '#title' => t('Area Code'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['area'],
    '#attributes' => $element['#attributes'],
  );
  $element['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['phone'],
    '#attributes' => $element['#attributes'],
  );
  $element['ext'] = array(
    '#type' => 'textfield',
    '#title' => t('Ext'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['ext'],
    '#attributes' => $element['#attributes'],
  );
  $element['mobile'] = array(
    '#type' => 'textfield',
    '#title' => t('Mobile'),
    '#title_display' => 'invisible',
    '#value' => $element['#value']['mobile'],
    '#attributes' => $element['#attributes'],
  );

  // Set default values.
  foreach ($default_values as $type => $value) {
    unset($element[$type]['#value']);
    $element[$type]['#default_value'] = isset($default_values[$type]) ? $default_values[$type] : NULL;
  }
  //print_r($element);exit;

  // Tweak the phone/mobile field.
  if (!$element['#mobile_textfield']) {
	$element['country']['#size'] = 5;
    $element['country']['#maxlength'] = 3;
	
	$element['area']['#size'] = 5;
    $element['area']['#maxlength'] = 4;
	
	$element['phone']['#size'] = 10;
    $element['phone']['#maxlength'] = 15;
	
	$element['ext']['#size'] = 5;
    $element['ext']['#maxlength'] = 6;
	
	unset($element['mobile']);
  }
  else {
	$element['country']['#size'] = 5;
    $element['country']['#maxlength'] = 3;
	  
	unset($element['area']);
	unset($element['phone']);
	unset($element['ext']);
	
	$element['mobile']['#size'] = 15;
    $element['mobile']['#maxlength'] = 15;
  }

  return $element;
}

/**
 * Theme a webform telephone element.
 */
function theme_webform_telephone($variables) {
  $element = $variables['element'];

  if (!$element['#mobile_textfield']) {
    $element['country']['#attributes']['class'] = array('country', 'number');
    $element['area']['#attributes']['class'] = array('area', 'number');
	$element['phone']['#attributes']['class'] = array('phone', 'number');
	$element['ext']['#attributes']['class'] = array('ext', 'number');
	if ($element['#required']) {
	  $element['country']['#attributes']['class'] = array('country', 'number', 'required');
	  $element['phone']['#attributes']['class'] = array('phone', 'number', 'required');
	}
  }
  else {
    $element['country']['#attributes']['class'] = array('country', 'number');
	$element['mobile']['#attributes']['class'] = array('mobile', 'number');
	if ($element['#required']) {
	  $element['country']['#attributes']['class'] = array('country', 'number', 'required');
	  $element['phone']['#attributes']['class'] = array('phone', 'number', 'required');
	}
  }

  // Add error classes to all items within the element.
  if (form_get_error($element)) {
    if (!$element['#mobile_textfield']) {
	  $element['country']['#attributes']['class'][] = 'error';
      $element['area']['#attributes']['class'][] = 'error';
      $element['phone']['#attributes']['class'][] = 'error';
	  $element['ext']['#attributes']['class'][] = 'error';
	}
	else {
	  $element['country']['#attributes']['class'][] = 'error';
	  $element['mobile']['#attributes']['class'][] = 'error';
	}
  }

  $class = array('webform-container-inline');

  // Add the JavaScript calendar if available (provided by Date module package).
  /*if (!empty($element['#datepicker'])) {
    $class[] = 'webform-datepicker';
    $calendar_class = array('webform-calendar');
    if ($element['#start_date']) {
      $calendar_class[] = 'webform-calendar-start-' . $element['#start_date'];
    }
    if ($element['#end_date']) {
      $calendar_class[] = 'webform-calendar-end-' . $element['#end_date'];
    }
    $calendar_class[] ='webform-calendar-day-' . variable_get('date_first_day', 0);

    $calendar = theme('webform_calendar', array('component' => $element['#webform_component'], 'calendar_classes' => $calendar_class));
  }*/

  $output = '';
  $output .= '<div class="' . implode(' ', $class) . '"> +';
  $output .= drupal_render_children($element);
  //$output .= isset($calendar) ? $calendar : '';
  $output .= '</div>';

  return $output;
}

/**
 * Element validation for Webform date fields.
 */
function webform_validate_telephone($element, $form_state) {
  // Check if the user filled the required fields.
  if ($element['#required']) {
    if (isset($element['country']) && empty($element['country']['#value'])) {
	  form_error($element, t('!name field is can not be empty.', array('!name' => $element['country']['#title']))); 
	}
	if (isset($element['phone']) && empty($element['phone']['#value'])) {
	  form_error($element, t('!name field is can not be empty.', array('!name' => $element['phone']['#title']))); 
	}
	if (isset($element['mobile']) && empty($element['mobile']['#value'])) {
	  form_error($element, t('!name field is can not be empty.', array('!name' => $element['mobile']['#title']))); 
	}
  }
  
  if (isset($element['country']) && !empty($element['country']['#value']) && (!is_numeric($element['country']['#value']) || strlen(trim($element['country']['#value']))>3 )) {
    form_error($element, t('!name field is required max 3 digits.', array('!name' => $element['country']['#title'])));
    //return;
  }
  if (isset($element['area']) && !empty($element['area']['#value']) && (!is_numeric($element['area']['#value']) || strlen(trim($element['area']['#value']))>4 )) {
    form_error($element, t('!name field is required max 4 digits.', array('!name' => $element['area']['#title'])));
    //return;
  }
  if (isset($element['phone']) && !empty($element['phone']['#value']) && (!is_numeric($element['phone']['#value']) || strlen(trim($element['phone']['#value']))>15 )) {
    form_error($element, t('!name field is required max 15 digits.', array('!name' => $element['phone']['#title'])));
    //return;
  }
  if (isset($element['ext']) && !empty($element['ext']['#value']) && (!is_numeric($element['ext']['#value']) || strlen(trim($element['ext']['#value']))>6 )) {
    form_error($element, t('!name field is required max 6 digits.', array('!name' => $element['ext']['#title'])));
    //return;
  }
  if (isset($element['mobile']) && !empty($element['mobile']['#value']) && (!is_numeric($element['mobile']['#value']) || strlen(trim($element['mobile']['#value']))>15 )) {
    form_error($element, t('!name field is required max 15 digits.', array('!name' => $element['mobile']['#title'])));
    //return;
  }
}

// Convert an array of a telephone into a string.
function webform_telephone_string($array, $type='phone') {
  $string = '';
  
  $i = 1;
  $arr = array('country', 'area', 'phone', 'ext', 'mobile');
  foreach ($arr as $field_type) {
	if (isset($array[$field_type])) {
	  $tag = ($i==count($arr)) ? "" : "|";
	  $string .= $array[$field_type].$tag;
	}
	$i++;
  }
  
  return $string;
}

/**
 * Implements _webform_submit_component().
 */
function _webform_submit_telephone($component, $value) {
  // Convert to a string.
  return webform_telephone_string($value);
}

/**
 * Implements _webform_display_component().
 */
function _webform_display_telephone($component, $value, $format = 'html') {
  if (isset($value[0]) && $value[0] !== '') {
    $type  = ($component['extra']['mobile_textfield']) ? "mobile" : "phone";
	$value = webform_telephone_array($value[0], $type);
  }
  
  return array(
    '#title' => $component['name'],
    '#weight' => $component['weight'],
    '#theme' => 'webform_display_telephone',
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
    '#format' => $format,
    '#value' => $value,
    '#translatable' => array('title'),
  );
}

/**
 * Format the text output for this component.
 */
function theme_webform_display_telephone($variables) {
  $element = $variables['element'];
  $output = '';
  if (isset($element['#value']['country']) && !empty($element['#value']['country'])) {
	$output .= '+'.$element['#value']['country']." ";
  }
  if (isset($element['#value']['area']) && !empty($element['#value']['area'])) {
	$output .= $element['#value']['area']." ";
  }
  if (isset($element['#value']['phone']) && !empty($element['#value']['phone'])) {
	$output .= $element['#value']['phone']."";
  }
  if (isset($element['#value']['ext']) && !empty($element['#value']['ext'])) {
	$output .= '-'.$element['#value']['ext'];
  }
  if (isset($element['#value']['mobile'])) {
	$output .= $element['#value']['mobile'];
  }

  return $output;
}

/**
 * Implements _webform_analysis_component().
 */
function _webform_analysis_telephone($component, $sids = array()) {
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
    ->fields('wsd', array('no', 'data'))
    ->condition('nid', $component['nid'])
    ->condition('cid', $component['cid'])
    ->orderBy('sid');

  if (count($sids)) {
    $query->condition('sid', $sids, 'IN');
  }

  $result = $query->execute();

  $dates = array();
  $submissions = 0;
  foreach ($result as $row) {
    $submissions++;
    if ($row['data']) {
      $dates[] = webform_telephone_array($row['data']);
    }
  }

  // Display stats.
  $nonblanks = count($dates);
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  $rows[1] = array(t('User entered value'), $nonblanks);
  return $rows;
}

/**
 * Implements _webform_table_component().
 */
function _webform_table_telephone($component, $value) { echo '88';exit;
  if ($value[0]) {
    //$timestamp = webform_strtotime($value[0]);
    //$format = webform_date_format('short');
    //return format_date($timestamp, 'custom', $format, 'UTC');
	
	return $value[0];
  }
  else {
    return '';
  }
}

/**
 * Implements _webform_csv_headers_component().
 */
function _webform_csv_headers_telephone($component, $export_options) {
  $header = array();
  $header[0] = '';
  $header[1] = '';
  $header[2] = $component['name'];
  return $header;
}

/**
 * Implements _webform_csv_data_component().
 */
function _webform_csv_data_telephone($component, $export_options, $value) {
  if ($value[0]) {
    //$timestamp = webform_strtotime($value[0]);
    //$format = webform_date_format('short');
    //return format_date($timestamp, 'custom', $format, 'UTC');
	return $value[0];
  }
  else {
    return '';
  }
}
